package com.kcyu.sfhinvoice.utils;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PdfToImageConverter {

    public static void main(String[] args) {
        try {
            // 加载 PDF 文件
            PDDocument document = Loader.loadPDF(new File("D:\\lls\\yujiancong\\Desktop\\测试证件\\发票\\发票好多张.pdf"));
//            PDDocument document = PDDocument.load(new File("input.pdf"));

            // 创建 PDF 渲染器
            PDFRenderer pdfRenderer = new PDFRenderer(document);


            // 循环处理每一页并将其转换为图片
            for (int page = 0; page < document.getNumberOfPages(); page++) {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300); // 300 DPI
                ImageIO.write(bim, "writePNG", new File("D:\\lls\\yujiancong\\Desktop\\测试证件\\发票\\converter\\" + page + ".png"));
            }

            // 关闭 PDF 文件
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void pdfToImage(String pdfPath, String imagePath) throws IOException {
            // 加载 PDF 文件
            PDDocument document = Loader.loadPDF(new File(pdfPath));
//            PDDocument document = PDDocument.load(new File("input.pdf"));

            // 创建 PDF 渲染器
            PDFRenderer pdfRenderer = new PDFRenderer(document);


            // 循环处理每一页并将其转换为图片
            for (int page = 0; page < document.getNumberOfPages(); page++) {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300); // 300 DPI
                ImageIO.write(bim, "writePNG", new File(imagePath));
            }

            // 关闭 PDF 文件
            document.close();
    }

}
